{{template "admin/header.html"}}
<title>update - gpress</title>
{{template "admin/bodystart.html"}}
{{ $tableFiled := tableFiled .urlPathParam }}
{{ $category := category }} <!-- 导航数据 -->
{{ $pageTemplate := pageTemplate }} <!-- 模版数据 -->

<style>
	.code-line .number{
		background-color: transparent;
		font-size: 12px;
		padding: 0;
		vertical-align: unset;
		margin-right: 0;
	}
</style>
<section class="section">
	<input type="hidden" id="content" value="{{.content}}">
	<input type="hidden" id="markdown" value="{{.markdown}}">
	<input type="hidden" id="thumbnail" value="{{.thumbnail}}">
	<input type="hidden" id="updateId" value="{{.id}}">
	<input type="hidden" id="categoryName" value="{{.categoryName}}">
	<input type="hidden" id="categoryID" value="{{.categoryID}}">
	<input type="hidden" id="templateName" value="{{.templateName}}">
	<input type="hidden" id="templateID" value="{{.templateID}}">

	<div class="container">
		<div class="table-content">
			<div class="column">
				<form id="gpress-form" action="{{basePath}}admin/{{.urlPathParam}}/update" method="POST">
					{{ $data := . }}
					<ul class="save-ul">
						<li>
							<div class="left">
								文章标题
							</div>
							<div class="right">
								<input class="input" type="text" name="title" value="{{.title}}" id="title" />
							</div>
						</li>
						<li>
							<div class="left">
								副标题
							</div>
							<div class="right">
								<input class="input" type="text" name="subtitle" value="{{.subtitle}}" id="subtitle">
							</div>
						</li>
						<li>
							<div class="left">
								文章ID
							</div>
							<div class="right">
								<input class="input" type="text" name="id" value="{{.id}}" id="id">
							</div>
						</li>
						<li>
							<div class="left">
								关键字
							</div>
							<div class="right">
								<input class="input" type="text" name=keyword value="{{.keyword}}" id="keyword">
							</div>
						</li>
						<li>
							<div class="left">
								页面模版
							</div>
							<div class="right">
								<select class="input" id="templateSelect">
									<option value="">请选择</option>
									{{ range $index,$obj := $pageTemplate }}
									<option value='{{$obj.id}}'>{{$obj.name}}</option>
									{{end}}
								</select>
							</div>
						</li>
						<li>
							<div class="left">
								导航名称
							</div>
							<div class="right">
								<select class="input" id="navSelect">
									<option value="">请选择</option>
									{{ range $index,$obj := $category }}
									<option value='{{$obj.id}}'>{{$obj.name}}</option>
									{{end}}
								</select>
							</div>
						</li>
						<li>
							<div class="left">
								tag标签
							</div>
							<div class="right">
								<input class="input" type="text" name="tag" value="{{.tag}}" id="tag">
							</div>
						</li>
						<li>
							<div class="left">
								作者
							</div>
							<div class="right">
								<input class="input" type="text" name="author" value="{{.author}}" id="author">
							</div>
						</li>
						<li style="align-items: flex-start;">
							<div class="left">
								封面图
							</div>
							<div class="right">
								<div class="upload-modlue">
									<div class="upload-box">
										<i class="iconfont icon-shangchuan"></i>
										<p>上传图片</p>
										<input class="input" type="file" id="fileInput">
									</div>
									<div class="img-box">
										<div class="img-preview">
											<img src="{{.thumbnail}}" id="img">
											<div class="delete-btn">
												<i class="iconfont icon-shanchu"></i>
											</div>
										</div>
									</div>
								</div>
							</div>
						</li>
						<li>
							<div class="left">
								排序
							</div>
							<div class="right">
								<input class="input" type="number" name="sortNo" value="{{.sortNo}}" id="sortNo">
							</div>
						</li>
						<li>
							<div class="left">
								排序
							</div>
							<div class="right">
								<input class="input" type="number" name="sortNo" id="sortNo">
							</div>
						</li>
						<li>
							<div class="left">
								文章内容
							</div>
							<div class="right">
								<div class="control">
									<label class="radio">
										<input type="radio" value="0" name="foobar" checked>
										富文本
									</label>
									<label class="radio">
										<input type="radio" value="1" name="foobar">
										Markdown
									</label>
								</div>
							</div>
						</li>
						<li id="editor-show" style="align-items: flex-start;">
							<div class="left">
							</div>
							<div class="right flex1">
								<div id="editor—wrapper">
									<div id="toolbar-container">
										<!-- 工具栏 -->
									</div>
									<div id="editor-container" style="height: 400px;">
										<!-- 编辑器 -->
									</div>
								</div>
							</div>
						</li>
						<li id="markdown-show" style="align-items: flex-start;display: none;">
							<div class="left">
							</div>
							<div class="right flex1" style="height: 500px;">
								<div id="markdown-container"></div>
							</div>
						</li>
					</ul>

					<div class="field is-grouped" style="padding-left: 190px;">
						<div class="control">
							<button type="submit" class="button is-primary">提交</button>
						</div>
						<div class="control">
							<button type="reset" class="button is-info is-light">重置</button>
						</div>
					</div>
				</form>
			</div>
		</div>
	</div>
</section>
<link href="https://cdn.staticfile.org/wangeditor5/5.1.23/css/style.min.css" rel="stylesheet">
<script src="https://cdn.staticfile.org/wangeditor5/5.1.23/index.min.js"></script>
<script type="text/javascript" src="{{basePath}}admin/js/cherry-markdown.min.js"></script>
<script>
	let categoryID = $('#categoryID').val()
	let categoryName = $('#categoryName').val()
	let templateID = $('#templateID').val()
	let templateName = $('#templateName').val()
	let content = ''
	let thumbnail = $('#thumbnail').val()
	
	$('#navSelect').val(categoryID)
	$('#templateSelect').val(templateID)
	
	$('#templateSelect').change(function(e) {
		templateID = $('#templateSelect').val()
		templateName = $('#templateSelect option:selected').text()
	})
	$('#navSelect').change(function(e) {
		categoryID = $('#navSelect').val()
		categoryName = $('#navSelect option:selected').text()
	})

	// 图片上传
	if (thumbnail) {
		$('.upload-box').hide()
		$('.img-box').show()
	}
	$('#fileInput').change(function(e) {
		let file = e.target.files[0]
		if (!/image\/\w+/.test(file.type)) {
			$.confirm({
				useBootstrap: false,
				boxWidth: '300px',
				title: '提示',
				content: '请上传图片格式！',
				type: 'red',
				buttons: { '确定': function() {} }
			})
			return false
		}
		var formdata = new FormData() // FormData对象，来发送二进制文件。
		formdata.append('file', e.currentTarget.files[0]) // 将文件追加到 formdata对象中
		$.ajax({
			type: 'post',
			url: '/admin/upload',
			data: formdata,
			processData: false,
			contentType: false,
			success(res) {
				thumbnail = res.data
				$('#img').attr('src', thumbnail) //将img的src属性的值赋值
				$('.upload-box').hide()
				$('.img-box').show()
			},
			error(err) {
				$.confirm({
					useBootstrap: false,
					boxWidth: '400px',
					title: '提示',
					content: '上传失败！',
					type: 'red',
					buttons: { '确定': function() {} }
				})
			}
		})
	})

	// 删除图片
	$('.delete-btn').click(function() {
		thumbnail = ''
		$('#fileInput').val('')
		$('#img').attr('src', '')
		$('.upload-box').show()
		$('.img-box').hide()
	})

	// markdown编辑器
	$(document).ready(function() {
		let fullScreen = Cherry.createMenuHook('全屏', 'full')
		window.cherryObj = new Cherry({
			id: 'markdown-container',
			value: $('#markdown').val(),
			toolbars: {
				toolbar: ['bold', 'italic', 'strikethrough', '|', 'color', 'header', '|', 'list', {
					insert: ['image', 'link', 'hr', 'br', 'code', 'formula',
						'toc', 'table', 'line-table', 'bar-table',
					]
				}, '|', 'full'],
				customMenu: {
					// 注入编辑器的菜单中
					// 对象 key 可以作为菜单项的名字（需要保证唯一），在上方的配置中使用
					'full': fullScreen,
				},
			},
			fileUpload(file, callback) {
				var formdata = new FormData() // FormData对象，来发送二进制文件。
				formdata.append('file', file) // 将文件追加到 formdata对象中
				$.ajax({
					type: 'post',
					url: '/admin/upload',
					data: formdata,
					processData: false,
					contentType: false,
					success(res) {
						callback(res.data)
					},
					error(err) {}
				})
			},
		})
		$('.cherry-toolbar-全屏').click(function(e) {
			if ($('#markdown-container').hasClass('full-screen')) {
				$('.cherry-toolbar-全屏').html('全屏')
				$('#markdown-container').removeClass('full-screen')
			} else {
				$('.cherry-toolbar-全屏').html('退出全屏')
				$('#markdown-container').addClass('full-screen')
			}
		})
	})

	// 单选切换
	$('input[name=\'foobar\']').click(function(e) {
		let current = $('input[name=\'foobar\']:checked').val()
		if (current == 0) {
			$('#editor-show').show()
			$('#markdown-show').hide()
		} else {
			$('#markdown-show').show()
			$('#editor-show').hide()
		}
	})
	
	// 判断markdown是否有值，有值优先显示markdown编辑器
	if($('#markdown').val()){
		$('#markdown-show').show()
		$('#editor-show').hide()
		$('input:radio[value=1]').attr('checked','true')
}

	// 判断markdown是否有值，有值优先显示markdown编辑器
	if ($('#markdown').val()) {
		$('#markdown-show').show()
		$('#editor-show').hide()
		$('input:radio[value=1]').attr('checked', 'true')
	}

	// 富文本编辑器
	const {
		createEditor,
		createToolbar
	} = window.wangEditor
	const editorConfig = {
		placeholder: '请输入内容...',
		MENU_CONF: {},
		onChange(editor) {
			content = editor.getHtml()
			// 也可以同步到 <textarea>
		}
	}
	editorConfig.MENU_CONF['uploadImage'] = {
		server: '/admin/upload',
		fieldName: 'file',
		customInsert(res, insertFn) { // 自定义返回数据结构。不用按照wangeditor默认规定的服务器返回的数据结构
			insertFn(res.data)
		},
		onSuccess(file, res) {
			console.log(res, '--上传成功---')
		},
		onFailed(file, res) {
			$.dialog({
				title: '提示',
				useBootstrap: false,
				boxWidth: '400px',
				content: '上传失败',
			})
		},
		onError(file, err, res) {
			console.log('--上传错误---')
		},
	}
	const editor = createEditor({
		selector: '#editor-container',
		html: $('#content').val(),
		config: editorConfig,
		mode: 'default', // or 'simple'
	})
	const toolbar = createToolbar({
		editor,
		selector: '#toolbar-container',
		config: {},
		mode: 'default', // or 'simple'
	})

	// 保存提交
	const form = document.getElementById('gpress-form')
	form.addEventListener('submit', async event => {
		event.preventDefault()
		const formData = new FormData(form)
		const jsonObject = {
			id: $('#updateId').val(),
			title: $('#title').val(),
			subtitle: $('#subtitle').val(),
			keyword: $('#keyword').val(),
			categoryID: categoryID,
			categoryName: categoryName,
			templateID: templateID,
			description: $('#description').val(),
			author: $('#author').val(),
			thumbnail: thumbnail,
			sortNo: $('#sortNo').val(),
			content: content,
			markdown: cherryObj.getMarkdown(),
		}
		console.log(jsonObject)
		const response = await fetch(form.action, {
			method: form.method,
			body: JSON.stringify(jsonObject),
			headers: { 'Content-Type': 'application/json' }
		})
		let res = await response.json()
		if (res.statusCode == 1) {
			$.confirm({
				useBootstrap: false,
				boxWidth: '400px',
				title: '提示',
				content: '修改成功！',
				type: 'green',
				buttons: {
					'确定': function() {
						window.location.href = '{{basePath}}admin/{{.urlPathParam}}/list'
					}
				}
			})
		} else {
			$.confirm({
				useBootstrap: false,
				boxWidth: '400px',
				title: '提示',
				content: res.message,
				type: 'red',
				buttons: { '确定': function() {} }
			})
		}
	})
</script>

{{template "admin/bodyend.html"}}
